<script type="text/javascript">
	$(document).ready(function() {
		document.title = "Aplicação do Algoritmo Filtering para Dados Agrícolas";

		// botão Voltar: retorna à página Home
		$('#back').click(function() {
			$.ajax({
				type:   'POST',
				url:    "HomeContent.php",
				data:   {},
				success: function(response) {
					$('#application').hide();
					$('#application').html("");
					$('#header').show();
					$('#wrapper').show();
					$('#footer').show();
					$('#content').html(response);
				},
				error: function(message){
					$('#content').html(message);
				}
			});
			return false;
		});

		// gera os mapas da aplicação requisitada após o algoritmo ser executado
		generateMaps();
	});

	function generateMaps() {
		OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=";
		OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
		OpenLayers.DOTS_PER_INCH = 25.4 / 0.28;
		var map;
		var options = {
			projection: new OpenLayers.Projection("EPSG:900913"),
			displayProjection: new OpenLayers.Projection("EPSG:4326"),
			// map horizontal units are meters
			units: "m",
			// this resolution displays the globe in one 256x256 pixel tile
			maxResolution: 156543.0339,
			// these are the bounds of the globe in sperical mercator
			maxExtent: new OpenLayers.Bounds(-20037508, -20037508,
			20037508, 20037508),
			controls: [new OpenLayers.Control.Navigation(),
				new OpenLayers.Control.PanZoomBar()]
		};
		map = new OpenLayers.Map('map',options);
		map.addControl(new OpenLayers.Control.LayerSwitcher());

		// cria as Layers do Google Maps
		var gphy = new OpenLayers.Layer.Google(
			"Google Physical",
			{type: G_PHYSICAL_MAP,'sphericalMercator': true}
		);
		var gmap = new OpenLayers.Layer.Google(
			"Google Street", // the default
			{'sphericalMercator': true}
		);
		var ghyb = new OpenLayers.Layer.Google(
			"Google Hybrid",
			{type: G_HYBRID_MAP,'sphericalMercator': true}
		);
		var gsat = new OpenLayers.Layer.Google(
			"Google Satellite",
			{type: G_SATELLITE_MAP,'sphericalMercator': true}
		);

		// cria as Layers do Yahoo! Maps
		var yahoo = new OpenLayers.Layer.Yahoo(
			"Yahoo Street",
			{'sphericalMercator': true}
		);
		var yahoosat = new OpenLayers.Layer.Yahoo(
			"Yahoo Satellite",
			{'type': YAHOO_MAP_SAT, 'sphericalMercator': true}
		);
		var yahoohyb = new OpenLayers.Layer.Yahoo(
			"Yahoo Hybrid",
			{'type': YAHOO_MAP_HYB, 'sphericalMercator': true}
		);

		var tile_shape = new OpenLayers.Layer.WMS(
			"Contorno do Talhão",
			"http://143.107.164.103:8081/cgi-bin/mapserv.exe?map=c:\\maps\\wms_filtering_contorno.map",
			{
				layers: "filtering_contorno",
				styles: '',
				srs: 'EPSG:4269',
				format: 'image/png',
				tiled: 'true',
				transparent: true
			},
			{
				'opacity': 0.75,
				'isBaseLayer': false,
				'wrapDateLine': true
			}
		);

		var productivity_after_filtering = new OpenLayers.Layer.WMS(
			"Produtividade de Milho Após Algoritmo",
			"http://143.107.164.103:8081/cgi-bin/mapserv.exe?map=c:\\maps\\wms_filtering_produtividade_depois.map",
			{
				layers: "filtering_produtividade_depois",
				styles: '',
				srs: 'EPSG:4269',
				format: 'image/png',
				tiled: 'true',
				transparent: true
			},
			{
				'opacity': 0.75,
				'isBaseLayer': false,
				'wrapDateLine': true
			}
		);

//		var jacto = new OpenLayers.Layer.WMS(
//			"Produtividade de Milho",
//			"http://143.107.164.103:8081/cgi-bin/mapserv.exe?map=c:\\maps\\wms_jacto.map",
//			{
//				layers: "jacto",
//				styles: '',
//				srs: 'EPSG:4269',
//				format: 'image/png',
//				tiled: 'true',
//				transparent: true
//			},
//			{
//				'opacity': 0.75,
//				'isBaseLayer': false,
//				'wrapDateLine': true
//			}
//		);

		var vectors = new OpenLayers.Layer.Vector(
			"Marcadores",
			{isBaseLayer: false}
		);

		// adiciona as Layers no Mapa Após do Algoritmo Filtering
		map.addLayers([ gphy,
						gmap,
						ghyb,
						gsat,
						//yahoo,		//não suporta zoom > 15
						//yahoohyb,		//não suporta zoom > 15
						//yahoosat,		//não suporta zoom > 15
						productivity_after_filtering,
						tile_shape,
						vectors]);

//		var info = new OpenLayers.Control.WMSGetFeatureInfo({
//			url: "http://143.107.164.103:8081/cgi-bin/mapserv.exe?map=c:\\maps\\wms_postgis.map",
//			title: 'Identify features by clicking',
//			queryVisible: true,
//			vendorParams: {
//				"FEATURE_COUNT": "1000"},
//			eventListeners: {
//				getfeatureinfo:
//					function(event) {
//					if((event.text).length != 1) {
//						map.addPopup(new OpenLayers.Popup.FramedCloud(
//						"chicken",
//						map.getLonLatFromPixel(event.xy),
//						null,
//						event.text,
//						null,
//						true
//					));
//					}
//				}
//			}
//		});
//		map.addControl(info);
//		info.activate();

		var report = function(e) {
			OpenLayers.Console.log(e.type, e.feature.id);
		};

		var highlightCtrl = new OpenLayers.Control.SelectFeature(vectors, {
			hover: true,
			highlightOnly: true,
			renderIntent: "temporary",
			eventListeners: {
				beforefeaturehighlighted: report,
				featurehighlighted: report,
				featureunhighlighted: report
			}
		});

		var selectCtrl = new OpenLayers.Control.SelectFeature(vectors,
			{clickout: true}
		);

		map.events.register("click", map,
		function(e) {
			// Read the map coordinates from the click event
			var lonlat = map.getLonLatFromViewPortPx(e.xy).transform(map.projection,map.displayProjection);
			// Construct the query URL
			var url = "ClickQueryAfterFiltering.php";
			url += "?lon=" + lonlat.lon;
			url += "&lat=" + lonlat.lat;

			// Load the URL into an iframe
			document.getElementById("query").src = url;
		});

		map.addControl(highlightCtrl);
		map.addControl(selectCtrl);
		map.addControl(new OpenLayers.Control.EditingToolbar(vectors));
		//map.addControl(new OpenLayers.Control.Scale($('scale')));
		map.addControl(new OpenLayers.Control.MousePosition({div: document.getElementById("location")}));
		map.addControl(new OpenLayers.Control.KeyboardDefaults);
		var panel = new OpenLayers.Control.Panel(
			{div: document.getElementById("panel")}
		);
		map.addControl(panel);
		var history = new OpenLayers.Control.NavigationHistory();
		map.addControl(history);
		panel.addControls(
			[history.next,
				history.previous]
		);
//		var longitude = -50.01526; // jacto
//		var latitude = -22.67936;  // jacto
		var longitude = -49.98771; <?php echo($longitude);  ?>
		var latitude = -22.69764;
		var zoom = 15;
		map.setCenter(new OpenLayers.LonLat(longitude, latitude).transform(map.displayProjection, map.projection), zoom);
		highlightCtrl.activate();
		selectCtrl.activate();

		// Mapa Antes do ALgoritmo
		var map_before_filtering;
		var options_before_filtering = {
			projection: new OpenLayers.Projection("EPSG:900913"),
			displayProjection: new OpenLayers.Projection("EPSG:4326"),
			// map horizontal units are meters
			units: "m",
			// this resolution displays the globe in one 256x256 pixel tile
			maxResolution: 156543.0339,
			// these are the bounds of the globe in sperical mercator
			maxExtent: new OpenLayers.Bounds(-20037508, -20037508,
			20037508, 20037508),
			controls: [new OpenLayers.Control.Navigation(),
				new OpenLayers.Control.PanZoomBar()]
		};

		map_before_filtering = new OpenLayers.Map('map_before_filtering', options_before_filtering);
		map_before_filtering.addControl(new OpenLayers.Control.LayerSwitcher());

		// cria as Layers do Google Maps
		var gphy_before_filtering = new OpenLayers.Layer.Google(
			"Google Physical",
			{type: G_PHYSICAL_MAP,'sphericalMercator': true}
		);
		var gmap_before_filtering = new OpenLayers.Layer.Google(
			"Google Street", // the default
			{'sphericalMercator': true}
		);
		var ghyb_before_filtering = new OpenLayers.Layer.Google(
			"Google Hybrid",
			{type: G_HYBRID_MAP,'sphericalMercator': true}
		);
		var gsat_before_filtering = new OpenLayers.Layer.Google(
			"Google Satellite",
			{type: G_SATELLITE_MAP,'sphericalMercator': true}
		);

		var tile_shape_before_filtering = new OpenLayers.Layer.WMS(
			"Contorno do Talhão",
			"http://143.107.164.103:8081/cgi-bin/mapserv.exe?map=c:\\maps\\wms_filtering_contorno.map",
			{
				layers: "filtering_contorno",
				styles: '',
				srs: 'EPSG:4269',
				format: 'image/png',
				tiled: 'true',
				transparent: true
			},
			{
				'opacity': 0.75,
				'isBaseLayer': false,
				'wrapDateLine': true
			}
		);

		var productivity_before_filtering = new OpenLayers.Layer.WMS(
			"Produtividade de Milho Antes do Algoritmo",
			"http://143.107.164.103:8081/cgi-bin/mapserv.exe?map=c:\\maps\\wms_filtering_produtividade_antes.map",
			{
				layers: "filtering_produtividade_antes",
				styles: '',
				srs: 'EPSG:4269',
				format: 'image/png',
				tiled: 'true',
				transparent: true
			},
			{
				'opacity': 0.75,
				'isBaseLayer': false,
				'wrapDateLine': true
			}
		);

		var vectors_before_filtering = new OpenLayers.Layer.Vector(
			"Marcadores",
			{isBaseLayer: false}
		);

		// adiciona as Layers no Mapa Antes do Algoritmo Filtering
		map_before_filtering.addLayers([ gphy_before_filtering,
										 gmap_before_filtering,
										 ghyb_before_filtering,
										 gsat_before_filtering,
										 productivity_before_filtering,
										 tile_shape_before_filtering,
										 vectors_before_filtering]);

		var report_before_filtering = function(e) {
			OpenLayers.Console.log(e.type, e.feature.id);
		};
		var highlightCtrl_before_filtering = new OpenLayers.Control.SelectFeature(vectors_before_filtering, {
			hover: true,
			highlightOnly: true,
			renderIntent: "temporary",
			eventListeners: {
				beforefeaturehighlighted: report_before_filtering,
				featurehighlighted: report_before_filtering,
				featureunhighlighted: report_before_filtering
			}
		});

		var selectCtrl_before_filtering = new OpenLayers.Control.SelectFeature(vectors_before_filtering,
			{clickout: true}
		);

		map_before_filtering.events.register("click", map_before_filtering,
		function(e) {
			// Read the map coordinates from the click event
			var lonlat_before_filtering = map_before_filtering.getLonLatFromViewPortPx(e.xy).transform(map_before_filtering.projection,map_before_filtering.displayProjection);

			// Construct the query URL
			var url_before_filtering = "ClickQueryBeforeFiltering.php";
			url_before_filtering += "?lon=" + lonlat_before_filtering.lon;
			url_before_filtering += "&lat=" + lonlat_before_filtering.lat;

			// Load the URL into an iframe
			document.getElementById("query_before_filtering").src = url_before_filtering;
		});
		map_before_filtering.addControl(highlightCtrl_before_filtering);
		map_before_filtering.addControl(selectCtrl_before_filtering);
		map_before_filtering.addControl(new OpenLayers.Control.EditingToolbar(vectors_before_filtering));
		//map_before_filtering.addControl(new OpenLayers.Control.Scale($('scale')));
		map_before_filtering.addControl(new OpenLayers.Control.MousePosition({div: document.getElementById("location_before_filtering")}));
		map_before_filtering.addControl(new OpenLayers.Control.KeyboardDefaults);
		var panel_before_filtering = new OpenLayers.Control.Panel(
			{div: document.getElementById("panel_before_filtering")}
		);
		map_before_filtering.addControl(panel_before_filtering);
		var history_before_filtering = new OpenLayers.Control.NavigationHistory();
		map_before_filtering.addControl(history_before_filtering);
		panel_before_filtering.addControls(
			[history_before_filtering.next,
				history_before_filtering.previous]
		);
		var longitude_before_filtering	= longitude;
		var latitude_before_filtering	= latitude
		var zoom_before_filtering		= zoom;
		map_before_filtering.setCenter(new OpenLayers.LonLat(longitude_before_filtering, latitude_before_filtering).transform(map_before_filtering.displayProjection, map_before_filtering.projection), zoom_before_filtering);
		highlightCtrl_before_filtering.activate();
		selectCtrl_before_filtering.activate();
	}
</script>

<div id="back"></div>

<table>
	<tr>
		<td>
			<div id="first_map">
				<h1 class="application">Aplicação Antes do Algoritmo <i>Filtering</i></h1>
				<div id="map_before_filtering" class="smallmap"></div>
				<div id="location_before_filtering" class="location">location</div>
				<div id="panel_before_filtering"></div>
				<iframe id="query_before_filtering"></iframe>
			</div>
		</td>
		<td>
			<div id="second_map">
				<h1 class="application">Aplicação Após Algoritmo <i>Filtering</i></h1>
				<div id="map" class="smallmap"></div>
				<div id="location" class="location">location</div>
				<?php
					// local em que os arquivos de entrada e saída ficam armazenados
					$context_path							= "C:\\\\data\\\\FilteringApp\\\\";
					// obtém os dados de entrada do algoritmo via HTTP POST Response
					$file_name_shape_map					= $_POST['file_shape_map'];
					$file_shape_map							= $context_path . $_POST['file_shape_map'];
					$file_name_original_productivity_map	= GetFileName($_POST['file_original_productivity_map']);
					$file_original_productivity_map			= $context_path . $_POST['file_original_productivity_map'];
					// arquivo de saída: Mapa de Produtividade após a aplicação do algoritmo Filtering
					$file_name_output						= "ceres_2_mapa_produtividade_filtrado.txt";
					$file_output							= $context_path . $file_name_output;

					// armazena os dados de entrada no Banco de Dados Espacial
					$schema_name = "filtering";
					$sql_create_schema = "DROP SCHEMA IF EXISTS " . $schema_name . " CASCADE;" . " "
										  .	"CREATE SCHEMA filtering
											 AUTHORIZATION postgres;";
					// armazena os dados de entrada do Mapa de Contorno fornecidos pelo usuário
					$tile_shape_table_name = "tile_shape";
					$sql_create_tile_shape_table = "CREATE TABLE " . $schema_name . "." . $tile_shape_table_name . " "
												    . "(
															latitude double precision,
															longitude double precision,
															altitude double precision
														)
														WITHOUT OIDS;";
					// copia os dados de entrada do Mapa de Contorno no formato padrão .TXT para o Banco de Dados Geoespacial
					// remove o cabeçalho de descrição dos campos para o arquivo de entrada do Mapa de Contorno
					removeLines($file_shape_map, 1);
					$sql_copy_tile_shape_txt_to_bd = "COPY " . $schema_name . "." . $tile_shape_table_name . " "
													 . "FROM " . "'" . $file_shape_map . "'" . ";";
					// adiciona a coluna TSID (i.e. tile_shape ID) à tabela de Mapa de Contorno
					$sql_add_tile_shape_id_column = "ALTER TABLE " . $schema_name . "." . $tile_shape_table_name		. " "
													 . "ADD COLUMN tsid serial NOT NULL;"								. " "
													 . "ALTER TABLE " . $schema_name . "." . $tile_shape_table_name		. " "
													 . "ADD CONSTRAINT tsid_pkey PRIMARY KEY (tsid);";
					//adiciona a coluna THEPOINT_LONLAT à tabela de Mapa de Contorno
					$tile_shape_geometry_column_name	= "thepoint_lonlat";
					$tile_shape_spatial_reference_id	= 4269;
					$tile_shape_type					= "POINT";
					$tile_shape_dimension				= 2;
					$sql_add_tile_shape_geometry_column = "SELECT AddGeometryColumn( "
														  . "'" . $schema_name						. "'" . ", "
														  . "'" . $tile_shape_table_name			. "'" . ", "
														  . "'" . $tile_shape_geometry_column_name	. "'" . ", "
																. $tile_shape_spatial_reference_id		  . ", "
														  . "'" . $tile_shape_type					. "'" . ", "
																. $tile_shape_dimension				      . " );";
					// preenche a coluna THEPOINT_LONLAT na tabela de Mapa de Contorno
					$sql_set_values_into_tile_shape_geometry_column = "UPDATE " . $schema_name . "." . $tile_shape_table_name												. " "
																	   . "SET " . $tile_shape_geometry_column_name															. " "
																	   . "= setsrid(makepoint(longitude, latitude), " . $tile_shape_spatial_reference_id . ");"				. " "
																	   . "CREATE INDEX idx_filtering_ts_thepoint_lonlat ON " . $schema_name . "." . $tile_shape_table_name	. " "
																	   . "USING GIST (" . $tile_shape_geometry_column_name . ");";
					// armazena os dados de entrada do Mapa de Produtividade fornecidos pelo usuário
					$productivity_map_before_table_name = "productivity_map_before";
					$sql_create_productivity_map_before_table = "CREATE TABLE " . $schema_name . "." . $productivity_map_before_table_name
																 . "(
																		id integer,
																		width double precision,
																		moisture double precision,
																		wet_lg_yld double precision,
																		latitude double precision,
																		longitude double precision,
																		fix_status integer,
																		tag_status integer,
																		east__x_ double precision,
																		north__y_ double precision,
																		distance_ double precision,
																		dist_north double precision,
																		dist_east double precision,
																		dry_yld double precision
																	 )
																	 WITHOUT OIDS;";
					// copia os dados de entrada do Mapa de Produtividade no formato padrão .TXT TABULADO para o Banco de Dados Geoespacial
					// remove o cabeçalho de descrição dos campos para o arquivo de entrada do Mapa de Produtividade
					removeLines($file_original_productivity_map, 1);
					$sql_copy_productivity_map_before_txt_to_bd = "COPY " . $schema_name . "." . $productivity_map_before_table_name . " "
																  . "FROM " . "'" . $file_original_productivity_map . "'" . ";";
					// adiciona a coluna PMBID (i.e. productivity_map_before ID ) à tabela de Mapa de Produtividade Antes do Filtering
					$sql_add_productivity_map_before_id_column = "ALTER TABLE " . $schema_name . "." . $productivity_map_before_table_name		. " "
																 . "ADD COLUMN pmbid serial NOT NULL;"								. " "
																 . "ALTER TABLE " . $schema_name . "." . $productivity_map_before_table_name		. " "
																 . "ADD CONSTRAINT pmbid_pkey PRIMARY KEY (pmbid);";
					//adiciona a coluna THEPOINT_LONLAT à tabela de Mapa de Produtividade Antes do Filtering
					$productivity_map_before_geometry_column_name		= "thepoint_lonlat";
					$productivity_map_before_spatial_reference_id		= 4269;
					$productivity_map_before_type						= "POINT";
					$productivity_map_before_dimension					= 2;
					$sql_add_productivity_map_before_geometry_column	= "SELECT AddGeometryColumn("
																		  . "'" . $schema_name									. "'" . ", "
																		  . "'" . $productivity_map_before_table_name			. "'" . ", "
																		  . "'" . $productivity_map_before_geometry_column_name	. "'" . ", "
																				. $productivity_map_before_spatial_reference_id		  . ", "
																		  . "'" . $productivity_map_before_type					. "'" . ", "
																				. $productivity_map_before_dimension				  . ");";
					// preenche a coluna THEPOINT_LONLAT na tabela de Mapa de Produtividade Antes do Filtering
					$sql_set_values_into_productivity_map_before_geometry_column = "UPDATE " . $schema_name . "." . $productivity_map_before_table_name												. " "
																				   . "SET " . $productivity_map_before_geometry_column_name															. " "
																				   . "= setsrid(makepoint(longitude, latitude), " . $productivity_map_before_spatial_reference_id . ");"				. " "
																				   . "CREATE INDEX idx_filtering_pmb_thepoint_lonlat ON " . $schema_name . "." . $productivity_map_before_table_name	. " "
																				   . "USING GIST (" . $productivity_map_before_geometry_column_name . ");";
					
					// executa o algoritmo Filtering
					$output_filtering_algorithm = shell_exec("java -jar filtragem.jar"
															. " " . $file_name_shape_map
															. " " . $file_shape_map
															. " " . $file_name_original_productivity_map
															. " " . $file_original_productivity_map
															. " " . $file_output);

					// armazena os dados gerados pelo algoritmo Filtering no Banco de Dados Espacial
					$productivity_map_after_table_name = "productivity_map_after";
					$sql_create_productivity_map_after_table = "CREATE TABLE " . $schema_name . "." . $productivity_map_after_table_name
																 . "(
																		id integer,
																		width double precision,
																		moisture double precision,
																		wet_lg_yld double precision,
																		latitude double precision,
																		longitude double precision,
																		fix_status integer,
																		tag_status integer,
																		east__x_ double precision,
																		north__y_ double precision,
																		distance_ double precision,
																		dist_north double precision,
																		dist_east double precision,
																		dry_yld double precision
																	 )
																	 WITHOUT OIDS;";
					// copia os dados de saída no formato padrão .TXT TABULADO para o Banco de Dados Geoespacial
					// remove o cabeçalho de descrição dos campos para o arquivo de saída
					removeLines($file_output, 1);
					$sql_copy_file_output_txt_to_bd = "COPY " . $schema_name . "." . $productivity_map_after_table_name . " "
																  . "FROM " . "'" . $file_output . "'" . ";";
					// adiciona a coluna PMAID (i.e. productivity_map_after ID ) à tabela de Mapa de Produtividade Antes do Filtering
					$sql_add_productivity_map_after_id_column = "ALTER TABLE " . $schema_name . "." . $productivity_map_after_table_name		. " "
																. "ADD COLUMN pmaid serial NOT NULL;"								. " "
																. "ALTER TABLE " . $schema_name . "." . $productivity_map_after_table_name		. " "
																. "ADD CONSTRAINT pmaid_pkey PRIMARY KEY (pmaid);";
					//adiciona a coluna THEPOINT_LONLAT à tabela de Mapa de Produtividade Após Filtering
					$productivity_map_after_geometry_column_name		= "thepoint_lonlat";
					$productivity_map_after_spatial_reference_id		= 4269;
					$productivity_map_after_type						= "POINT";
					$productivity_map_after_dimension					= 2;
					$sql_add_productivity_map_after_geometry_column	= "SELECT AddGeometryColumn("
																		  . "'" . $schema_name									. "'" . ", "
																		  . "'" . $productivity_map_after_table_name			. "'" . ", "
																		  . "'" . $productivity_map_after_geometry_column_name	. "'" . ", "
																				. $productivity_map_after_spatial_reference_id		  . ", "
																		  . "'" . $productivity_map_after_type					. "'" . ", "
																				. $productivity_map_after_dimension					  . ");";
					// preenche a coluna THEPOINT_LONLAT na tabela de Mapa de Produtividade Após Filtering (dados georeferenciados de saída)
 					$sql_set_values_into_productivity_map_after_geometry_column = "UPDATE " . $schema_name . "." . $productivity_map_after_table_name												. " "
																				   . "SET " . $productivity_map_after_geometry_column_name															. " "
																				   . "= setsrid(makepoint(longitude, latitude), " . $productivity_map_after_spatial_reference_id . ");"				. " "
																				   . "CREATE INDEX idx_filtering_pma_thepoint_lonlat ON " . $schema_name . "." . $productivity_map_after_table_name	. " "
																				   . "USING GIST (" . $productivity_map_after_geometry_column_name . ");";

					// executa os scripts para armazzenar os dados de entrada e os dados de saída gerados pelo algoritmo Filetring
					$database = pg_connect("dbname=postgis user=postgres password=tcc09")
								or die("Não foi possível estabelecer conexão ao Banco da Dados.");
					pg_query($database, $sql_create_schema);
					pg_query($database, $sql_create_tile_shape_table);
					pg_query($database, $sql_copy_tile_shape_txt_to_bd);
					pg_query($database, $sql_add_tile_shape_id_column);
					pg_query($database, $sql_add_tile_shape_geometry_column);
					pg_query($database, $sql_set_values_into_tile_shape_geometry_column);
					pg_query($database, $sql_create_productivity_map_before_table);
					pg_query($database, $sql_copy_productivity_map_before_txt_to_bd);
					pg_query($database, $sql_add_productivity_map_before_id_column);
					pg_query($database, $sql_add_productivity_map_before_geometry_column);
					pg_query($database, $sql_set_values_into_productivity_map_before_geometry_column);
					pg_query($database, $sql_create_productivity_map_after_table);
					pg_query($database, $sql_copy_file_output_txt_to_bd);
					pg_query($database, $sql_add_productivity_map_after_id_column);
					pg_query($database, $sql_add_productivity_map_after_geometry_column);
					pg_query($database, $sql_set_values_into_productivity_map_after_geometry_column);
					pg_close($database);

					// Custom Functions
					function removeLines($txtfile, $numlines)  {
						if (file_exists("temp.txt"))
							unlink("temp.txt");
						$arrayz = file("$txtfile");
						$tempWrite = fopen("temp.txt", "w");
						for ($i = $numlines; $i < count($arrayz); $i++)
							fputs($tempWrite, "$arrayz[$i]");
						fclose($tempWrite);
						copy("temp.txt", "$txtfile");
						unlink("temp.txt");
					}

					function GetFileName($filepath) {
						preg_match('/[^?]*/', $filepath, $matches);
						$string = $matches[0];
						#split the string by the literal dot in the filename
						$pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);
						#get the last dot position
						$lastdot = $pattern[count($pattern)-1][1];
						#now extract the filename using the basename function
						$filename = basename(substr($string, 0, $lastdot-1));
						#return the filename part
						return $filename;
					}
				?>
				<div id="panel"></div>
				<iframe id="query"></iframe>
			</div>
	   </td>
	</tr>
</table>